from wx import wx
import glob
import os
import AddMediaDialog
import sqlite3
import base64
import wx.media

# will need to set a flag somehow to switch between win, linux and mac, if i want my app to be cross platform

class CreateMediaTab(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.toolbar_ADDMEDIA = wx.NewId()
        self.toolbar_DELMEDIA = wx.NewId()
        self.toolbar_UPDATEMEDIA = wx.NewId()
        self.toolbar_PLAYMEDIA = wx.NewId()
        self.toolbar_PAUSEMEDIA = wx.NewId()
        self.toolbar_STOPMEDIA = wx.NewId()
        
        self.mediaFilePath = ""
        self.mediaListBox = wx.ListBox(self, -1, size=wx.Size(100, -1), style= wx.BORDER_SUNKEN | wx.LB_SINGLE | wx.LB_NEEDED_SB)
        
        box = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1, "Title:")
        label.SetHelpText("Tooltip that is displayed for the media.")
        box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL)

        self.mediaTitleText = wx.TextCtrl(self, -1, "", size=(250,-1))
        self.mediaTitleText.SetHelpText("Enter Media Tooltip")
        box.Add(self.mediaTitleText, 1, wx.ALIGN_CENTRE|wx.ALL)

        box2 = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1, "Alternate Text:")
        label.SetHelpText("Alternative Text for Accessibility.")
        box2.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL)

        self.mediaAltText = wx.TextCtrl(self, -1, "", size=(250,-1))
        self.mediaAltText.SetHelpText("Enter Textual Represent for the media.")
        box2.Add(self.mediaAltText, 1, wx.ALIGN_CENTRE|wx.ALL)
        
        box3 = wx.BoxSizer(wx.HORIZONTAL)
        label = wx.StaticText(self, -1, "File Extension:")
        label.SetHelpText("File Type")
        box3.Add(label, 0, wx.ALIGN_LEFT | wx.ALL)
        
        self.mediaExtText = wx.TextCtrl(self, -1, "", size=(50, -1))
        self.mediaExtText.SetHelpText("File Extension")
        box3.Add(self.mediaExtText, 1, wx.ALIGN_LEFT | wx.ALL)
        
        self.mediaPanel = wx.Panel(self, style=wx.BORDER_SUNKEN)
        self.mediaToolbar = self.MakeMediaToolbar()
        self.mainBox = wx.BoxSizer(wx.VERTICAL)
        self.botBox = wx.BoxSizer(wx.HORIZONTAL)
        self.topBox = wx.BoxSizer(wx.HORIZONTAL)
        self.horBox = wx.BoxSizer(wx.HORIZONTAL)
        self.verBox = wx.BoxSizer(wx.VERTICAL)
        self.horBox.Add(box, 0, wx.ALL | wx.ALIGN_LEFT)
        self.horBox.Add(box3, 0, wx.ALL | wx.ALIGN_LEFT)
        self.verBox.Add(self.horBox, 0, wx.ALL | wx.ALIGN_LEFT)
        self.verBox.Add(box2, 0, wx.ALL | wx.ALIGN_LEFT, 1)
        self.verBox.Add(self.mediaPanel, 1, wx.EXPAND, 1)
        self.topBox.Add(self.mediaToolbar, 1, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.mediaListBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.verBox, 1, wx.EXPAND)
        self.mainBox.Add(self.topBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.mainBox.Add(self.botBox, 1, wx.EXPAND)
        self.SetSizer(self.mainBox)

        wx.EVT_LISTBOX(self, self.mediaListBox.GetId(), self.OnSelectedMediaItem)

    def MakeMediaToolbar(self):
        tb = wx.ToolBar(self, -1, style=wx.TB_FLAT | wx.NO_BORDER)
        self.ToolBar = tb
        tb.AddTool(self.toolbar_ADDMEDIA, wx.Bitmap("images/list-add.png", wx.BITMAP_TYPE_PNG), isToggle=False, shortHelpString="Add Media")
        tb.AddTool(self.toolbar_DELMEDIA, wx.Bitmap("images/list-remove.png", wx.BITMAP_TYPE_PNG), shortHelpString="Remove Selected Media")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_PLAYMEDIA, wx.Bitmap("images/media-playback-start.png", wx.BITMAP_TYPE_PNG), shortHelpString="Play")
        tb.AddTool(self.toolbar_PAUSEMEDIA, wx.Bitmap("images/media-playback-pause.png", wx.BITMAP_TYPE_PNG), shortHelpString="Pause")
        tb.AddTool(self.toolbar_STOPMEDIA, wx.Bitmap("images/media-playback-stop.png", wx.BITMAP_TYPE_PNG), shortHelpString="Stop")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_UPDATEMEDIA, wx.Bitmap("images/document-save.png", wx.BITMAP_TYPE_PNG), shortHelpString="Save Media Text")
        
        tb.EnableTool(self.toolbar_DELMEDIA, False)
        tb.EnableTool(self.toolbar_UPDATEMEDIA, False)
        tb.EnableTool(self.toolbar_PAUSEMEDIA, False)
        tb.EnableTool(self.toolbar_PLAYMEDIA, False)
        tb.EnableTool(self.toolbar_STOPMEDIA, False)
        
        wx.EVT_TOOL(self, self.toolbar_ADDMEDIA, self.AddMedia)
        wx.EVT_TOOL(self, self.toolbar_DELMEDIA, self.DelMedia)
        wx.EVT_TOOL(self, self.toolbar_UPDATEMEDIA, self.UpdateMedia)
        wx.EVT_TOOL(self, self.toolbar_PAUSEMEDIA, self.PauseMedia)
        wx.EVT_TOOL(self, self.toolbar_PLAYMEDIA, self.PlayMedia)
        wx.EVT_TOOL(self, self.toolbar_STOPMEDIA, self.StopMedia)
        
        tb.Realize()
        
        return tb
    
    def OnSelectedMediaItem(self, event):
        if(self.mediaListBox.GetSelection() != -1):
            if(self.mediaPanel.GetChildren() != []):
                self.mediaPanel.DestroyChildren()
            delPath = self.TopLevelParent.GetAppPath() + "/tmpMedia.*"
            tmpFileList = glob.glob(delPath)
            for tmpFile in tmpFileList:
                os.remove(tmpFile)
                
            self.mediaToolbar.EnableTool(self.toolbar_DELMEDIA, True)
            self.mediaToolbar.EnableTool(self.toolbar_UPDATEMEDIA, True)
            tmpString = self.mediaListBox.GetStringSelection()
            tmpId = int(tmpString.split(".", 1)[0])
            self.data = base64.decodestring(self.TopLevelParent.currentMediaDict[tmpId][0])
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("SELECT layout FROM ResourceTable WHERE resourceID = (?)", (tmpId,))
            for row in cur:
                tmpAltText = row[0].split("::")[0]
                tmpTitleText = row[0].split("::")[1]
                tmpExtension = row[0].split("::")[2]
            
            self.mediaAltText.SetValue(tmpAltText)
            self.mediaTitleText.SetValue(tmpTitleText)
            self.mediaExtText.SetValue(tmpExtension)
            self.mediaExtText.SetEditable(False)
            self.mediaExtText.Enable(False)
            
            tmpMediaFile = self.TopLevelParent.GetAppPath() + "/tmpMedia." + tmpExtension
            self.tmpFile = open(self.TopLevelParent.opj(tmpMediaFile), "wb+")
            self.tmpFile.write(self.data)
            self.tmpFile.close()
            self.mediaPlayer = wx.media.MediaCtrl(self.mediaPanel, style=wx.BORDER_SIMPLE, szBackend=wx.media.MEDIABACKEND_WMP10) # win only right now
            wx.media.EVT_MEDIA_LOADED(self, -1, self.OnMediaLoaded)
            self.mediaPlayer.Load(tmpMediaFile)
            
    def OnMediaLoaded(self, event):
        self.mediaPlayer.SetInitialSize()
        self.TopLevelParent.DisplayDebug("audio loaded")
        self.mediaToolbar.EnableTool(self.toolbar_PAUSEMEDIA, True)
        self.mediaToolbar.EnableTool(self.toolbar_PLAYMEDIA, True)
        self.mediaToolbar.EnableTool(self.toolbar_STOPMEDIA, True)
        
    def AddMedia(self, event):
        self.addMediaDialog = AddMediaDialog.AddMediaDialog(self, -1, "Add Media to Course", size=(350, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.addMediaDialog.CenterOnParent()
        
        if(self.addMediaDialog.ShowModal() == wx.ID_OK):
            self.data = open(self.TopLevelParent.opj(self.addMediaDialog.mediaFileText.GetValue()), "rb").read()
            self.layoutValue = self.addMediaDialog.mediaAltText.GetValue() + "::" + self.addMediaDialog.mediaTitleText.GetValue() + "::" + self.addMediaDialog.mediaFileText.GetValue().rsplit(".", 1)[1]
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("INSERT INTO ResourceTable(resourceTypeID, layout, resourceData, courseID) VALUES(4, ?, ?, ?)", (self.layoutValue, base64.encodestring(sqlite3.Binary(self.data)), self.TopLevelParent.currentCourseID))
            lastID = cur.lastrowid
            con.commit()
            con.close()
            self.TopLevelParent.currentMediaDict = self.TopLevelParent.RefreshListBox(self.mediaListBox, self.TopLevelParent.currentCourseID, 4, None)
            if(self.mediaPanel.GetChildren() != []):
                self.mediaPanel.DestroyChildren()
            delPath = self.TopLevelParent.GetAppPath() + "/tmpMedia.*"
            tmpFileList = glob.glob(delPath)
            for tmpFile in tmpFileList:
                os.remove(tmpFile)
            
            self.mediaPlayer = wx.media.MediaCtrl(self.mediaPanel, style=wx.BORDER_SIMPLE, szBackend=wx.media.MEDIABACKEND_WMP10) # win only right now
            wx.media.EVT_MEDIA_LOADED(self, -1, self.OnMediaLoaded)
            self.mediaPlayer.Load(self.addMediaDialog.mediaFileText.GetValue())
            self.mediaAltText.SetValue(self.addMediaDialog.mediaAltText.GetValue())
            self.mediaExtText.SetValue(self.addMediaDialog.mediaFileText.GetValue().rsplit(".", 1)[0])
            self.mediaTitleText.SetValue(self.addMediaDialog.mediaTitleText.GetValue())
            self.mediaExtText.Enable(False)
            self.mediaExtText.SetEditable(False)
            self.mediaListBox.SetSelection(self.mediaListBox.FindString(str(lastID) + ". " + self.addMediaDialog.mediaTitleText.GetValue()))
            
        self.addMediaDialog.Destroy()
        
    def DelMedia(self, event):
        tmpString = self.mediaListBox.GetStringSelection()
        tmpString2 = tmpString.split(".", 1)
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("DELETE FROM ResourceTable WHERE resourceID = (?)", (int(tmpString2[0]),))
        con.commit()
        con.close()
        self.TopLevelParent.currentMediaDict = self.TopLevelParent.RefreshListBox(self.mediaListBox, self.TopLevelParent.currentCourseID, 4, None)

        if(self.mediaPanel.GetChildren() != []):
            self.mediaPanel.DestroyChildren()
        delPath = self.TopLevelParent.GetAppPath() + "/tmpMedia.*"
        tmpFileList = glob.glob(delPath)
        for tmpFile in tmpFileList:
            os.remove(tmpFile)
        
        self.TopLevelParent.DisplayDebug("del audio")
        
    def UpdateMedia(self, event):
        tmpString = self.mediaListBox.GetStringSelection()
        tmpId = int(tmpString.split(".", 1)[0])
        self.layoutValue = self.mediaAltText.GetValue() + "::" + self.mediaTitleText.GetValue() + "::" + self.mediaExtText.GetValue()
        tmpExtension = self.mediaExtText.GetValue()
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("UPDATE ResourceTable set layout = (?) where resourceID = (?)", (self.layoutValue, tmpId))
        con.commit()
        con.close()
        self.TopLevelParent.currentMediaDict = self.TopLevelParent.RefreshListBox(self.mediaListBox, self.TopLevelParent.currentCourseID, 4, None)
        self.data = base64.decodestring(self.TopLevelParent.currentMediaDict[tmpId][0])
        tmpMediaFile = self.TopLevelParent.GetAppPath() + "/tmpMedia." + tmpExtension
        self.tmpFile = open(self.TopLevelParent.opj(tmpMediaFile), "wb+")
        self.tmpFile.write(self.data)
        self.tmpFile.close()
        self.mediaPlayer = wx.media.MediaCtrl(self.mediaPanel, style=wx.BORDER_SIMPLE, szBackend=wx.media.MEDIABACKEND_WMP10) # win only right now
        wx.media.EVT_MEDIA_LOADED(self, -1, self.OnMediaLoaded)
        self.mediaPlayer.Load(tmpMediaFile)
        self.mediaListBox.SetSelection(self.mediaListBox.FindString(str(tmpId) + ". " + self.addMediaDialog.mediaTitleText.GetValue()))
        self.TopLevelParent.DisplayDebug("update audio")
        
    def PauseMedia(self, event):
        self.mediaPlayer.Pause()
        
    def PlayMedia(self, event):
        self.mediaPlayer.Play()
    
    def StopMedia(self, event):
        self.mediaPlayer.Stop()